package com.example.demo3network;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.lang.ref.WeakReference;

public class CountDownTimeActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int COUNTDOWN_TIME_CODE = 100001;
    public static final int DELAY_MILLIS = 1000;
    public static final int MAX_COUNT = 10;
    private TextView countTimeTextView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_count_down_time);
        findViews();
        setListener();

        CountDownTimeHandler handler = new CountDownTimeHandler(this, getMainLooper());

        Message message = Message.obtain();
        message.what = COUNTDOWN_TIME_CODE;
        message.arg1 = MAX_COUNT;

        handler.sendMessageDelayed(message, DELAY_MILLIS);
    }

    public static class CountDownTimeHandler extends Handler {
        final WeakReference<CountDownTimeActivity> mWeakReference;
        public CountDownTimeHandler(CountDownTimeActivity activity, Looper looper) {
            super(looper);
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            CountDownTimeActivity activity = mWeakReference.get();

            switch (msg.what) {
                case COUNTDOWN_TIME_CODE:
                    int value = msg.arg1;
                    activity.countTimeTextView.setText(String.valueOf(value--));

                    if (value > 0) {
                        Message message = Message.obtain();
                        message.what = COUNTDOWN_TIME_CODE;
                        message.arg1 = value;
                        sendMessageDelayed(message, DELAY_MILLIS);
                    }
                    break;
            }
        }
    }

    void findViews() {

        countTimeTextView = findViewById(R.id.countDownTimeTextView);

    }

    void setListener() {

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();

    }
}
